package com.example.qiniutest.aliyun.oss.service.impl;

import com.aliyun.oss.*;
import com.example.qiniutest.aliyun.oss.config.ALiYunOSSConfig;
import com.example.qiniutest.aliyun.oss.service.IALiYunOSSService;
import com.example.qiniutest.aliyun.oss.util.HexadecimalEncryption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ALiYunOSServiceImpl implements IALiYunOSSService {


    @Autowired
    private ALiYunOSSConfig config;

    @Autowired
    private HexadecimalEncryption encryption;

    @Autowired
    private ClientBuilderConfiguration configuration;


    @Override
    public Map<String,String> upload(MultipartFile file, String path) {
        String bucketName = config.getBucketName();
        //对文件进行加密   保留文件格式
        String objectName = createFilePath(file,path);

        OSS ossClient = createOssClient();
        log.info(objectName);
        Map<String,String> res=new HashMap<>();
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (OSSException e) {
            e.printStackTrace();
            res.put("error",e.getMessage());
            res.put("msg","上传失败");
            return res;
        } catch (IOException e) {
            e.printStackTrace();
            res.put("error",e.getMessage());
            res.put("msg","上传失败");
            return res;
        } finally {
            ossClient.shutdown();
        }
        objectName="/"+objectName;
        res.put("downUrl",config.getBucketOrg()+objectName);
        res.put("previewUrl",config.getUrl()+objectName);
        res.put("msg","上传成功");
        return res;
    }

    private OSS createOssClient(){
        String endpoint = config.getEndpoint();
        String accessKeyId = config.getAccessKeyId();
        String accessKeySecret = config.getAccessKeySecret();
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, configuration);
    }

    private String createFilePath(MultipartFile file, String path){
        String objectName="";
        try {
            String originalFilename = file.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            //加密
            String fileName = encryption.encryption(originalFilename.substring(0, i));
            String suffix = originalFilename.substring(i);
            objectName = path + "/" + fileName + suffix;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objectName;
    }

}
